package com.csp.session;

import cn.hutool.core.bean.BeanUtil;
import com.csp.anotation.mng.MethodMapping;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 存储sql执行时可变的信息
 *
 * @author:chengsp
 * @createTime:2019/8/22 15:25
 */
public class ExecuteMsg {

    /**
     * 方法参数
     */
    private Object[] args;

    /**
     * 方法映射对象
     */
    private MethodMapping methodMapping;

    /**
     * preparedStatement中setObject值
     */
    private Object[] paramValues;
    /**
     * sql参数和值的映射
     */
    private Map<String, Object> paramValueMap;

    public ExecuteMsg(Object[] args, MethodMapping methodMapping) {
        this.args = args;
        this.methodMapping = methodMapping;
        init();
    }

    private void init() {
        // 为空则代表没有被初始化过
        if (methodMapping.getOriginalSql() == null) {
            methodMapping.init();
        }
        List<String> paramList = methodMapping.getParamList();
        paramValues = new Object[paramList.size()];
        for (int j = 0; j < paramList.size(); j++) {
            String paramName = paramList.get(j);
            if (paramName.contains(".")) {

            } else {
                paramValues[j] = BeanUtil.getFieldValue(args[0], paramName);
            }
        }
    }

    /**
     * 给预编译语句添加参数
     * @param preparedStatement
     */
    public void setParams(PreparedStatement preparedStatement) {
        for (int i = 0; i < paramValues.length; i++) {
            try {
                preparedStatement.setObject(i + 1, paramValues[i]);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String s = "select * from table where arg1 = #{abc.hg}  and arg2=#{thb}";
    }


    public Object[] getArgs() {
        return args;
    }

    public void setArgs(Object[] args) {
        this.args = args;
    }

    public Object[] getParamValues() {
        return paramValues;
    }

    public void setParamValues(Object[] paramValues) {
        this.paramValues = paramValues;
    }

    public MethodMapping getMethodMapping() {
        return methodMapping;
    }

    public void setMethodMapping(MethodMapping methodMapping) {
        this.methodMapping = methodMapping;
    }

    public Map<String, Object> getParamValueMap() {
        return paramValueMap;
    }

}
